<template>
  <div class="materials-container">
    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <el-card>
        <div style="margin-bottom: 20px; text-align: right;">
          <el-button 
            type="primary" 
            @click="goToUpload"
            v-if="userStore.isLoggedIn && (userStore.isVIP || userStore.isAdmin)"
          >
            <el-icon><upload /></el-icon>
            上传资料
          </el-button>
        </div>
        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
            v-model="searchParams.keyword"
            placeholder="搜索资料"
            prefix-icon="Search"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </div>

        <!-- 分类筛选 -->
        <div class="filter-item">
          <div class="filter-label">资料分类：</div>
          <div class="filter-content">
            <el-radio-group v-model="searchParams.category" @change="handleSearch">
              <el-radio-button label="">全部</el-radio-button>
              <el-radio-button
                v-for="category in categories"
                :key="category.id"
                :label="category.id"
              >
                {{ category.name }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <!-- 标签筛选 -->
        <div class="filter-item">
          <div class="filter-label">标签：</div>
          <div class="filter-content">
            <el-check-tag
              v-for="tag in tags"
              :key="tag.id"
              :checked="selectedTags.includes(tag.id)"
              @change="handleTagChange(tag.id)"
              style="margin-right: 8px; margin-bottom: 8px;"
            >
              {{ tag.name }}
            </el-check-tag>
          </div>
        </div>

        <!-- 排序方式 -->
        <div class="filter-item">
          <div class="filter-label">排序方式：</div>
          <div class="filter-content">
            <el-radio-group v-model="searchParams.sort" @change="handleSearch">
              <el-radio-button label="latest">最新上传</el-radio-button>
              <el-radio-button label="downloads">下载最多</el-radio-button>
              <el-radio-button label="price-asc">价格从低到高</el-radio-button>
              <el-radio-button label="price-desc">价格从高到低</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 资料列表 -->
    <div class="materials-list">
      <el-row :gutter="20">
        <el-col
          v-for="material in materials"
          :key="material.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card class="material-card" shadow="hover" @click="goToMaterial(material.id)">
            <!-- 资料缩略图 -->
            <div class="material-thumbnail" @click="viewMaterial(material.id)">
              <img :src="material.thumbnail" :alt="material.title" />
              <div class="material-price">{{ material.price }} 虚拟币</div>
              <div class="material-type">{{ material.fileType }}</div>
            </div>

            <!-- 资料信息 -->
            <div class="material-info">
              <h3 class="material-title" @click="goToMaterial(material.id)">
                {{ material.title }}
              </h3>
              
              <!-- 资料标签 -->
              <div class="material-tags">
                <el-tag
                  v-for="tag in material.tags"
                  :key="tag"
                  size="small"
                  class="material-tag"
                >
                  {{ tag }}
                </el-tag>
              </div>

              <!-- 资料元信息 -->
              <div class="material-meta">
                <span class="material-date">{{ material.uploadDate }}</span>
                <span class="material-downloads">
                  <el-icon><Download /></el-icon>
                  {{ material.downloads }}
                </span>
              </div>

              <!-- 操作按钮 -->
              <div class="material-actions">
                <el-button
                  type="primary"
                  size="small"
                  @click="viewMaterial(material.id)"
                >
                  查看详情
                </el-button>
                <el-button
                  type="success"
                  size="small"
                  @click="addToCart(material)"
                  :disabled="!isLoggedIn"
                >
                  加入购物车
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 未登录提示 -->
    <el-dialog
      v-model="showLoginDialog"
      title="提示"
      width="30%"
      :show-close="false"
    >
      <span>请先登录后再进行操作</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showLoginDialog = false">取消</el-button>
          <el-button type="primary" @click="goToLogin">
            去登录
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Download, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

const router = useRouter()
const route = useRoute()

// 搜索参数
const searchParams = reactive({
  keyword: '',
  category: '',
  sort: 'latest',
  tags: []
})

// 分页参数
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 模拟数据
const categories = [
  { id: 1, name: '建筑工程' },
  { id: 2, name: 'IT招标' },
  { id: 3, name: '政府采购' },
  { id: 4, name: '设备采购' },
  { id: 5, name: '服务外包' }
]

const tags = [
  { id: 1, name: '2024年' },
  { id: 2, name: '最新' },
  { id: 3, name: '热门' },
  { id: 4, name: '推荐' },
  { id: 5, name: '精品' }
]

const selectedTags = ref([])

// 模拟资料数据
const materials = ref([
  {
    id: 1,
    title: '2024年政府采购标书模板（完整版）',
    thumbnail: 'https://via.placeholder.com/300x200/409EFF/FFFFFF?text=资料1',
    price: 5,
    fileType: 'DOCX',
    tags: ['2024年', '最新'],
    uploadDate: '2024-01-15',
    downloads: 1256,
    category: '政府采购'
  },
  // ... 更多资料数据
])

// 登录状态（后续会通过Pinia管理）
const isLoggedIn = ref(false)
const showLoginDialog = ref(false)

// 初始化
onMounted(() => {
  // 从路由参数中获取搜索条件
  const { keyword, category } = route.query
  if (keyword) searchParams.keyword = keyword
  if (category) searchParams.category = Number(category)
  
  // 加载资料列表
  loadMaterials()
})

// 加载资料列表
const loadMaterials = async () => {
  try {
    // TODO: 调用API获取资料列表
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
    total.value = 100 // 模拟总数据量
  } catch (error) {
    console.error('加载资料列表失败:', error)
    ElMessage.error('加载资料列表失败，请稍后重试')
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadMaterials()
}

// 标签切换
const handleTagChange = (tagId) => {
  const index = selectedTags.value.indexOf(tagId)
  if (index === -1) {
    selectedTags.value.push(tagId)
  } else {
    selectedTags.value.splice(index, 1)
  }
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadMaterials()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadMaterials()
}

// 查看资料详情
const viewMaterial = (id) => {
  router.push(`/material/${id}`)
}

// 加入购物车
const addToCart = (material) => {
  if (!isLoggedIn.value) {
    showLoginDialog.value = true
    return
  }
  
  // TODO: 实现加入购物车逻辑
  ElMessage.success('已加入购物车')
}

// 跳转到登录页
const goToLogin = () => {
  showLoginDialog.value = false
  router.push('/login')
}

const goToUpload = () => {
  router.push('/materials/upload')
}

const goToMaterial = (id) => {
  router.push(`/material/${id}`)
}
</script>

<style scoped>
.materials-container {
  padding: 1rem 0;
}

.filter-section {
  margin-bottom: 2rem;
}

.search-box {
  margin-bottom: 1.5rem;
}

.filter-item {
  margin-bottom: 1rem;
  display: flex;
  align-items: flex-start;
}

.filter-label {
  width: 100px;
  color: #606266;
  line-height: 32px;
}

.filter-content {
  flex: 1;
}

.material-card {
  margin-bottom: 1.5rem;
  transition: all 0.3s;
  cursor: pointer;
}

.material-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.material-thumbnail {
  position: relative;
  height: 150px;
  overflow: hidden;
  cursor: pointer;
}

.material-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.material-price {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(64, 158, 255, 0.9);
  color: white;
  padding: 0.3rem 0.6rem;
  border-radius: 4px;
  font-weight: bold;
}

.material-type {
  position: absolute;
  bottom: 10px;
  left: 10px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 0.2rem 0.4rem;
  border-radius: 4px;
  font-size: 0.8rem;
}

.material-info {
  padding: 1rem 0;
}

.material-title {
  margin: 0 0 0.5rem;
  font-size: 1rem;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.material-title:hover {
  color: #409EFF;
}

.material-tags {
  margin-bottom: 0.5rem;
}

.material-tag {
  margin-right: 0.5rem;
  margin-bottom: 0.5rem;
}

.material-meta {
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 0.9rem;
  margin-bottom: 1rem;
}

.material-downloads {
  display: flex;
  align-items: center;
  gap: 0.3rem;
}

.material-actions {
  display: flex;
  gap: 0.5rem;
}

.pagination-container {
  margin-top: 2rem;
  text-align: center;
}
</style>